import Vue from 'vue'
import VueRouter from 'vue-router'
// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store/index'
import util from '@/libs/util.js'

// 路由数据
import { defaultRoutes, errorPageRoutes, frameInRoutes, frameOutRoutes } from './routes'
import { userMenu } from '@/api/system/user'

const _import = require('@/libs/util.import.' + process.env.NODE_ENV)

// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return VueRouterPush.call(this, location).catch(err => err)
}
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
  return VueRouterReplace.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

// 导出路由 在 main.js 里使用
// const router = new VueRouter({
//   routes
// })
const createRouter = config => new VueRouter(config)
const router = createRouter({
  mode: 'history',
  routes: [...frameInRoutes, ...frameOutRoutes]
})

// 重置路由
// eslint-disable-next-line no-unused-vars
const resetRoutes = () => {
  router.matcher = createRouter({
    mode: 'history',
    routes: []
  }).matcher
}

/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {
  // console.info('去哪里', to)
  // 确认已经加载多标签页数据 https://github.com/d2-projects/d2-admin/issues/201
  await store.dispatch('d2admin/page/isLoaded')
  // 确认已经加载组件尺寸设置 https://github.com/d2-projects/d2-admin/issues/198
  await store.dispatch('d2admin/size/isLoaded')
  // 进度条
  NProgress.start()
  // 关闭搜索面板
  store.commit('d2admin/search/set', false)
  // 这里暂时将cookie里是否存有token作为验证是否登录的条件
  // 请根据自身业务需要修改
  const token = util.storage.getToken()
  // 验证当前路由所有的匹配中是否需要有登录验证的
  if (!util.isBlank(token)) {
    await fetchPermissionInfo(to, next)
    next()
  } else if (!to.matched.some(r => r.meta.auth)) {
    next()
  } else {
    // 没有登录的时候跳转到登录界面
    // 携带上登陆成功之后需要跳转的页面完整路径
    next({
      name: 'login',
      query: {
        redirect: to.fullPath
      }
    })
    // https://github.com/d2-projects/d2-admin/issues/138
    NProgress.done()
  }
})

const getMenu = async (callback) => {
  const menus = store.getters['d2admin/menu/getUserMenu'] || []
  if (menus.length > 0) {
    const treeMenus = util.treeMenu(menus, 'pid', 'children')
    callback(treeMenus, menus)
    return
  }
  userMenu().then(e => {
    const treeMenus = util.treeMenu(e, 'pid', 'children')
    callback(treeMenus, e)
  })
}

const fetchPermissionInfo = async (to) => {
  // console.info('当前路由', router.getRoutes())
  const load = store.getters['d2admin/menu/getRouteLoad']
  // await store.dispatch('d2admin/menu/menuSetting', null, { root: true })
  // console.info('获取到菜单加载：', load, to)
  if (load) {
    await Promise.resolve()
    return
  }
  if (to.name === 'login') {
    return
  }
  await getMenu((treeMenu, menuList) => {
    if (!load && menuList.length > 0) {
      const children = []
      for (const t of menuList) {
        if (t.router !== '') {
          try {
            children.push({
              path: `/${t.router}`,
              name: t.path === 'index' ? 'index' : t.router,
              meta: {
                title: t.name,
                auth: true
              },
              component: _import(t.router)
            })
          } catch (e) {
            console.error('添加动态路由错误:', e)
          }
        }
      }
      defaultRoutes.children.push(...children)
      const routers = [defaultRoutes, ...frameOutRoutes, ...errorPageRoutes]
      // store.commit('d2admin/menu/headerSet', e)
      // 持久化设置菜单
      store.dispatch('d2admin/menu/setMenu', treeMenu, { root: true })
      // 处理路由 得到每一级的路由设置
      store.commit('d2admin/page/init', routers)
      resetRoutes()
      // console.info('路由：：：', routers)
      // console.info('菜单：：：', treeMenu)
      routers.forEach(e => {
        router.addRoute(e)
      })
      store.commit('d2admin/menu/routeLoading')
    }
  })

  await Promise.resolve()
}
router.afterEach(to => {
  // 进度条
  NProgress.done()
  // 多页控制 打开新的页面
  store.dispatch('d2admin/page/open', to)
  // 更改标题
  util.title(to.meta.title)
})

export default router
